package eteam.aps.common.helper;

import eteam.aps.common.exceptions.DelimiterException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * ClassName LimitHelper
 *
 * @author Ll
 * @since 2024/5/22
 * Description 简单时间限流
 */
public class LimitHelper {

    /**
     * 限流集合
     */
    private static final Map<String, Long> LIMIT = new ConcurrentHashMap<>();

    /**
     * 限流
     *
     * @param key  键
     * @param time 时间
     * @param unit 单位
     */
    public synchronized static void limit(String key, int time, TimeUnit unit) {
        long now = System.currentTimeMillis();
        // 清楚已经过期的key
        List<String> keys = new ArrayList<>();
        LIMIT.forEach((k, v) -> {
            if (now > v) keys.add(k);
        });
        keys.forEach(LIMIT::remove);
        Long limit = LIMIT.get(key);
        if (limit == null) {
            LIMIT.put(key, System.currentTimeMillis() + unit.toMillis(time));
            return;
        }
        if (now < limit) throw new DelimiterException("该接口以限流，请稍后尝试~");
    }

    public synchronized static void removeLimit(String key) {
        LIMIT.remove(key);
    }

    public synchronized static void limit(String key, int time) {
        limit(key, time, TimeUnit.SECONDS);
    }

    public synchronized static void limit(String key) {
        limit(key, 10, TimeUnit.SECONDS);
    }

}
